package com.dycong.common.IO.netty.frame_coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;

/**
 * Created by dycong on 2017/4/17.
 *todo 继承LengthFieldBasedFrameDecoder 实现方法decode()，自定义解码器，转化为自己需要的entity，按照事先的约定 RPC应用!!!
 *todo -> http://blog.csdn.net/linuu/article/details/51371595
 */
public class MyLengthFieldBasedFrameDecoder extends LengthFieldBasedFrameDecoder {
    public MyLengthFieldBasedFrameDecoder(
            int maxFrameLength,
            int lengthFieldOffset, int lengthFieldLength) {
        this(maxFrameLength, lengthFieldOffset, lengthFieldLength, 0, 0, true);
    }

    public MyLengthFieldBasedFrameDecoder(
            int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
            int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(
                ByteOrder.BIG_ENDIAN, maxFrameLength, lengthFieldOffset, lengthFieldLength,
                lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        if (null == in)
            throw new RuntimeException("in is null??");
        if (in.readableBytes()<6)
            throw new RuntimeException("msg'length < header.length???");
        Msg msg=new Msg();
        msg.setType(in.readByte());
        msg.setStatus(in.readByte());
        msg.setLength(in.readInt());
        if (in.readableBytes()!= msg.length)
            throw new RuntimeException("length no equal");

        ByteBuf byteBuf=in.readBytes(msg.length);
        byte[] bytes=new byte[msg.length];
        byteBuf.readBytes(bytes);
        String s=new String(bytes,"utf-8");
        msg.setBody(s);
        return msg;
    }
}


